package com.qinggeng.project.tool.third.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.google.common.collect.Maps;
import com.qinggeng.common.enums.StatusEnum;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.DateUtils;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.common.utils.http.HttpUtils;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.system.domain.SysUser;
import com.qinggeng.project.system.domain.UserBind;
import com.qinggeng.project.system.domain.UserBindGsd;
import com.qinggeng.project.system.mapper.UserBindGsdMapper;
import com.qinggeng.project.system.mapper.UserBindMapper;
import com.qinggeng.project.system.service.ISysUserService;
import com.qinggeng.project.tool.third.domain.SysThird;
import com.qinggeng.project.tool.third.domain.SysThirdPlatform;
import com.qinggeng.project.tool.third.domain.vo.AccessTokenBean;
import com.qinggeng.project.tool.third.domain.vo.UserInfoBean;
import com.qinggeng.project.tool.third.domain.vo.UserInfoQqBean;
import com.qinggeng.project.tool.third.mapper.SysThirdPlatformMapper;
import com.qinggeng.project.tool.third.service.ISysThirdPlatformService;
import com.qinggeng.project.tool.third.service.ISysThirdService;
import com.qinggeng.project.tool.third.utils.AuthUtil;
import com.qinggeng.project.tool.third.utils.MiniappUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 第三方平台信息Service业务层处理
 *
 * @author qinggeng
 * @date 2020-03-13
 */
@Service
public class SysThirdPlatformServiceImpl implements ISysThirdPlatformService
{
    @Resource
    private SysThirdPlatformMapper sysThirdPlatformMapper;

    @Autowired
    private ISysThirdService thirdService;

    @Autowired
    private ISysUserService sysUserService;

    @Resource
    private UserBindMapper userBindMapper;

    @Resource
    private UserBindGsdMapper userBindGsdMapper;

    @Override
    public SysThirdPlatform selectSysThirdPlatformById(Long platformId) {
        return sysThirdPlatformMapper.selectSysThirdPlatformById(platformId);
    }

    @Override
    public List<SysThirdPlatform> selectSysThirdPlatformList(SysThirdPlatform sysThirdPlatform) {
        return sysThirdPlatformMapper.selectSysThirdPlatformList(sysThirdPlatform);
    }

    @Override
    public int insertSysThirdPlatform(SysThirdPlatform sysThirdPlatform) {
        return sysThirdPlatformMapper.insertSysThirdPlatform(sysThirdPlatform);
    }

    @Override
    public int updateSysThirdPlatform(SysThirdPlatform sysThirdPlatform) {
        return sysThirdPlatformMapper.updateSysThirdPlatform(sysThirdPlatform);
    }

    @Override
    public int deleteSysThirdPlatformByIds(Long[] platformIds) {
        return sysThirdPlatformMapper.deleteSysThirdPlatformByIds(platformIds);
    }

    @Override
    public int deleteSysThirdPlatformById(Long platformId) {
        return sysThirdPlatformMapper.deleteSysThirdPlatformById(platformId);
    }

    @Override
    public String aliPayToWebAuth(String redirectUri) throws Exception {
        SysThirdPlatform alipayConfig = sysThirdPlatformMapper.selectSysThirdPlatformByCode("alipay");
        return "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" + alipayConfig.getAppId() + "&scope=auth_user&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8");
    }

    @Override
    public String alipayToAppAuth(String platform) throws Exception {
        SysThirdPlatform alipayConfig = sysThirdPlatformMapper.selectSysThirdPlatformByCode(platform);
        JSONObject otherParams = JSON.parseObject(alipayConfig.getOtherParams());

        String token=System.currentTimeMillis()+new Random().nextInt()+"";
        String   targetId=null;
        try {
            MessageDigest md=MessageDigest.getInstance("md5");
            byte[] md5=md.digest(token.getBytes());
            BASE64Encoder base64Encoder = new BASE64Encoder();
            targetId = base64Encoder.encode(md5);
            System.out.println(targetId);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        SortedMap<String,String > map = new TreeMap<String,String >();
        map.put("apiname","com.alipay.account.auth");
        map.put("method","alipay.open.auth.sdk.code.get");
        map.put("app_id", 	alipayConfig.getAppId());
        map.put("app_name","mc");
        map.put("biz_type","openservice");
        map.put("pid", alipayConfig.getAppSecret());
        map.put("product_id","APP_FAST_LOGIN");
        map.put("scope","kuaijie");
        map.put("target_id",targetId);
        map.put("auth_type","AUTHACCOUNT");
        map.put("sign_type","RSA2");
        String signStr = AlipaySignature.getSignContent(map);
        String sign = AlipaySignature.rsa256Sign(signStr,otherParams.getString("privateKey"), "UTF-8");
        return signStr+ "&sign=" + URLEncoder.encode(sign,"UTF-8");
    }


    @Transactional
    @Override
    public SysThird aliPayAppToThirdInfo(String appAuthCode) throws Exception {
        SysThirdPlatform alipayConfig = sysThirdPlatformMapper.selectSysThirdPlatformByCode("alipayByGgzy");
        JSONObject otherParams = JSON.parseObject(alipayConfig.getOtherParams());
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", alipayConfig.getAppId(), otherParams.getString("APP_PRIVATE_KEY"), "json", "UTF-8", otherParams.getString("APP_PUBLIC_KEY"), "RSA2");
        AlipaySystemOauthTokenRequest oauthTokenRequest = new AlipaySystemOauthTokenRequest();
        oauthTokenRequest.setCode(appAuthCode);
        oauthTokenRequest.setGrantType("authorization_code");
        AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(oauthTokenRequest);
        if (!oauthTokenResponse.isSuccess()) {
            throw new CustomException("获取app_auth_token失败:" + oauthTokenResponse.getSubMsg());
        }
        // 根据appAuthToken换取用户信息
        AlipayUserInfoShareRequest userInfoShareRequest = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse userInfoShareResponse = alipayClient.execute(userInfoShareRequest,oauthTokenResponse.getAccessToken());

        if (!userInfoShareResponse.isSuccess()) {
            throw new RuntimeException("获取用户授权信息失败！" + userInfoShareResponse.getSubMsg());
        }
        //相同平台下 唯一ID查询 查找用户

        SysThird sysThird = thirdService.selectSysThirdByPlatform(alipayConfig.getPlatformCode(), userInfoShareResponse.getUserId());
        if (sysThird == null) {
            sysThird = new SysThird();
            SysUser sysUser = new SysUser();
            sysUser.setNickName(userInfoShareResponse.getNickName());
            sysUser.setAvatar(userInfoShareResponse.getAvatar());
            sysUser.setUserType(UserTypeEnum.MEMBER.getCode());
            if (userInfoShareResponse.getGender().equals("F")){
                sysUser.setSex("1");
            }
            if (userInfoShareResponse.getGender().equals("M")){
                sysUser.setSex("0");
            }
            sysUser.setStatus(StatusEnum.OK.getCode());
            sysUserService.insertUser(sysUser);
            sysThird.setUserId(sysUser.getUserId());

            sysThird.setPlatform(alipayConfig.getPlatformCode());
//            sysThird.setOpenId(userInfoShareResponse.getUserId());
//            sysThird.setAccessToken(oauthTokenResponse.getAccessToken());
//            sysThird.setRefreshToken(oauthTokenResponse.getRefreshToken());
//            sysThird.setExpiresIn(oauthTokenResponse.getExpiresIn());
            thirdService.insertSysThird(sysThird);
        } else {
//            sysThird.setAccessToken(oauthTokenResponse.getAccessToken());
//            sysThird.setRefreshToken(oauthTokenResponse.getRefreshToken());
//            sysThird.setExpiresIn(oauthTokenResponse.getExpiresIn());
//            sysThird.setOpenName(userInfoShareResponse.getNickName());
            thirdService.updateSysThird(sysThird);

            SysUser sysUser = sysUserService.selectUserById(sysThird.getUserId());
            sysUser.setAvatar(userInfoShareResponse.getAvatar());
            sysUserService.updateUser(sysUser);
        }
        return sysThird;
    }

    /**
     * 支付宝绑定 gsd
     * @param appAuthCode
     */
    @Override
    @Transactional
    public void alipayBindByGsd(String appAuthCode) throws Exception {
        //根据用户ID和平台查询是否绑定过支付宝
        UserBindGsd userBindGsd = userBindGsdMapper.selectUserBindGsdByUserIdAndPlatform(ApiUtils.getUserId(), "alipay");
        //isBind=1是绑定
        if (userBindGsd != null && userBindGsd.getIsBind().equals("1")){
            throw new CustomException("已绑定");
        }
        SysThirdPlatform alipayConfig = sysThirdPlatformMapper.selectSysThirdPlatformByCode("alipayByGsd");
        JSONObject otherParams = JSON.parseObject(alipayConfig.getOtherParams());
       // AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", alipayConfig.getAppId(), otherParams.getString("APP_PRIVATE_KEY"), "json", "UTF-8", otherParams.getString("APP_PUBLIC_KEY"), "RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", alipayConfig.getAppId(),
                otherParams.getString("privateKey"), "json", "UTF-8", otherParams.getString("publicKey"), "RSA2");
        AlipaySystemOauthTokenRequest oauthTokenRequest = new AlipaySystemOauthTokenRequest();
        oauthTokenRequest.setCode(appAuthCode);
        oauthTokenRequest.setGrantType("authorization_code");
        AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(oauthTokenRequest);
        if (!oauthTokenResponse.isSuccess()) {
            throw new CustomException("获取app_auth_token失败:" + oauthTokenResponse.getSubMsg());
        }
        // 根据appAuthToken换取用户信息
        AlipayUserInfoShareRequest userInfoShareRequest = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse userInfoShareResponse = alipayClient.execute(userInfoShareRequest,oauthTokenResponse.getAccessToken());

        if (!userInfoShareResponse.isSuccess()) {
            throw new RuntimeException("获取用户授权信息失败！" + userInfoShareResponse.getSubMsg());
        }
        String userId = userInfoShareResponse.getUserId();
        //isBind=0未绑定，且openid相等,绑定
        if (userBindGsd !=null && userBindGsd.getIsBind().equals("0") && userBindGsd.getUniqueId().equals(userId)){
            int result = userBindGsdMapper.updateUserBindGsdByUserIdAndPlatform(ApiUtils.getUserId(), "alipay");
            if (result == 1){
                return;
            }
            throw new CustomException("绑定失败,result="+result);
        }

        //isBind=0未绑定，且openid不相等,绑定
        if (userBindGsd !=null && userBindGsd.getIsBind().equals("0") && !userBindGsd.getUniqueId().equals(userId)){
            int result = userBindGsdMapper.deleteUserBindGsd(ApiUtils.getUserId(), "alipay");
            if (result != 1){
                throw new CustomException("绑定失败,result="+result);
            }
        }
        //绑定支付宝
        userBindGsd = new UserBindGsd();
        //设置登录用户ID
        userBindGsd.setUserId(ApiUtils.getUserId());
        userBindGsd.setRealUserName(userInfoShareResponse.getNickName());
        userBindGsd.setAvatar(userInfoShareResponse.getAvatar());
        userBindGsd.setPlatform("alipay");
        //提现账号
        userBindGsd.setUniqueId(userInfoShareResponse.getUserId());
        userBindGsd.setCreateTime(DateUtils.getNowDate());
        int result = userBindGsdMapper.insertUserBindGsd(userBindGsd);
        if (result <= 0){
            throw new CustomException("信息绑定失败，result="+result);
        }
    }

    /**
     * 支付宝绑定 ggzy
     * @param appAuthCode
     */
    @Override
    @Transactional
    public void alipayBind(String appAuthCode) throws Exception {
        //根据用户ID和平台查询是否绑定过支付宝
        UserBind userBind = userBindMapper.selectUserBindByUserIdAndPlatform(ApiUtils.getUserId(), "alipay");
        //isBind=1是绑定
        if (userBind != null && userBind.getIsBind().equals("1")){
            throw new CustomException("已绑定");
        }
        SysThirdPlatform alipayConfig = sysThirdPlatformMapper.selectSysThirdPlatformByCode("alipayByGgzy");
        JSONObject otherParams = JSON.parseObject(alipayConfig.getOtherParams());
        // AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", alipayConfig.getAppId(), otherParams.getString("APP_PRIVATE_KEY"), "json", "UTF-8", otherParams.getString("APP_PUBLIC_KEY"), "RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", alipayConfig.getAppId(),
                otherParams.getString("privateKey"), "json", "UTF-8", otherParams.getString("publicKey"), "RSA2");
        AlipaySystemOauthTokenRequest oauthTokenRequest = new AlipaySystemOauthTokenRequest();
        oauthTokenRequest.setCode(appAuthCode);
        oauthTokenRequest.setGrantType("authorization_code");
        AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(oauthTokenRequest);
        if (!oauthTokenResponse.isSuccess()) {
            throw new CustomException("获取app_auth_token失败:" + oauthTokenResponse.getSubMsg());
        }
        // 根据appAuthToken换取用户信息
        AlipayUserInfoShareRequest userInfoShareRequest = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse userInfoShareResponse = alipayClient.execute(userInfoShareRequest,oauthTokenResponse.getAccessToken());

        if (!userInfoShareResponse.isSuccess()) {
            throw new RuntimeException("获取用户授权信息失败！" + userInfoShareResponse.getSubMsg());
        }
        String userId = userInfoShareResponse.getUserId();
        //isBind=0未绑定，且openid相等,绑定
        if (userBind !=null && userBind.getIsBind().equals("0") && userBind.getUniqueId().equals(userId)){
            int result = userBindMapper.updateUserBindByUserIdAndPlatform(ApiUtils.getUserId(), "alipay");
            if (result == 1){
                return;
            }
            throw new CustomException("绑定失败,result="+result);
        }

        //isBind=0未绑定，且openid不相等,绑定
        if (userBind !=null && userBind.getIsBind().equals("0") && !userBind.getUniqueId().equals(userId)){
            int result = userBindMapper.deleteUserBind(ApiUtils.getUserId(), "alipay");
            if (result != 1){
                throw new CustomException("绑定失败,result="+result);
            }
        }
        //绑定支付宝
        userBind = new UserBind();
        //设置登录用户ID
        userBind.setUserId(ApiUtils.getUserId());
        userBind.setRealUserName(userInfoShareResponse.getNickName());
        userBind.setAvatar(userInfoShareResponse.getAvatar());
        userBind.setPlatform("alipay");
        //提现账号
        userBind.setUniqueId(userInfoShareResponse.getUserId());
        userBind.setCreateTime(DateUtils.getNowDate());
        int result = userBindMapper.insertUserBind(userBind);
        if (result <= 0){
            throw new CustomException("信息绑定失败，result="+result);
        }
    }

    /**
     * 微信绑定
     * @param code
     */
    @Override
    @Transactional
    public void wxBind(String code) throws Exception{
            //根据用户ID和平台查询是否绑定过支付宝
            UserBind userBind = userBindMapper.selectUserBindByUserIdAndPlatform(ApiUtils.getUserId(), "wx");
            //isBind=1是绑定
            if (userBind != null && userBind.getIsBind().equals("1")){
                throw new CustomException("已绑定");
            }
            SysThirdPlatform thirdPlatform = sysThirdPlatformMapper.selectSysThirdPlatformByCode("wxByGgzy");
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + thirdPlatform.getAppId() + "&secret="
                    + thirdPlatform.getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
            JSONObject jsonObject = AuthUtil.doGetJson(url);
            String openid = jsonObject.getString("openid");
            String token = jsonObject.getString("access_token");
            if(StringUtils.isBlank(openid)&&StringUtils.isBlank(token)){
                throw new CustomException("未获取到用户openid 或 token:"+JSON.toJSONString(token));
            }
            //isBind=0未绑定，且openid相等,绑定
            if (userBind !=null && userBind.getIsBind().equals("0") && userBind.getUniqueId().equals(openid)){
                int result = userBindMapper.updateUserBindByUserIdAndPlatform(ApiUtils.getUserId(), "wx");
                if (result == 1){
                    return;
                }
                throw new CustomException("绑定失败,result="+result);
            }

            //isBind=0未绑定，且openid不相等,绑定
            if (userBind !=null && userBind.getIsBind().equals("0") && !userBind.getUniqueId().equals(openid)){
                int result = userBindMapper.deleteUserBind(ApiUtils.getUserId(), "wx");
                if (result != 1){
                    throw new CustomException("绑定失败,result="+result);
                }
            }

            Map<String,String> querys = Maps.newHashMap();
            querys.put("access_token",token);
            querys.put("openid",openid);
            HttpResponse userinfoResponse = HttpUtils.doGet("https://api.weixin.qq.com", "/sns/userinfo", null, querys);
            JSONObject userinfoObject = JSON.parseObject(EntityUtils.toString(userinfoResponse.getEntity(), "UTF-8"));
            userBind = new UserBind();
            userBind.setAvatar(userinfoObject.getString("headimgurl"));
            userBind.setPlatform("wx");
            userBind.setRealUserName(userinfoObject.getString("nickname"));
            userBind.setUniqueId(userinfoObject.getString("openid"));
            userBind.setUserId(ApiUtils.getUserId());
            userBind.setCreateTime(DateUtils.getNowDate());
            int result = userBindMapper.insertUserBind(userBind);
            if (result <= 0){
                throw new CustomException("信息绑定失败，result="+result);
            }
    }

    /**
     * 微信绑定 gsd
     * @param
     */
    @Override
    @Transactional
    public void wxBindByGsd(String openid,String accessToken) throws Exception{
        //根据用户ID和平台查询是否绑定过支付宝
        UserBindGsd userBindGsd = userBindGsdMapper.selectUserBindGsdByUserIdAndPlatform(ApiUtils.getUserId(), "wx");
        //isBind=1是绑定
        if (userBindGsd != null && userBindGsd.getIsBind().equals("1")){
            throw new CustomException("已绑定");
        }
        //isBind=0未绑定，且openid相等,绑定
        if (userBindGsd !=null && userBindGsd.getIsBind().equals("0") && userBindGsd.getUniqueId().equals(openid)){
            int result = userBindGsdMapper.updateUserBindGsdByUserIdAndPlatform(ApiUtils.getUserId(), "wx");
            if (result == 1){
                return;
            }
            throw new CustomException("绑定失败,result="+result);
        }

        //isBind=0未绑定，且openid不相等,绑定
        if (userBindGsd !=null && userBindGsd.getIsBind().equals("0") && !userBindGsd.getUniqueId().equals(openid)){
            int result = userBindGsdMapper.deleteUserBindGsd(ApiUtils.getUserId(), "wx");
            if (result != 1){
                throw new CustomException("绑定失败,result="+result);
            }
        }

        Map<String,String> querys = Maps.newHashMap();
        querys.put("access_token",accessToken);
        querys.put("openid",openid);
        HttpResponse userinfoResponse = HttpUtils.doGet("https://api.weixin.qq.com", "/sns/userinfo", null, querys);
        JSONObject userinfoObject = JSON.parseObject(EntityUtils.toString(userinfoResponse.getEntity(), "UTF-8"));
        userBindGsd = new UserBindGsd();
        userBindGsd.setAvatar(userinfoObject.getString("headimgurl"));
        userBindGsd.setPlatform("wx");
        userBindGsd.setRealUserName(userinfoObject.getString("nickname"));
        userBindGsd.setUniqueId(userinfoObject.getString("openid"));
        userBindGsd.setUserId(ApiUtils.getUserId());
        userBindGsd.setCreateTime(DateUtils.getNowDate());
        int result = userBindGsdMapper.insertUserBindGsd(userBindGsd);
        if (result <= 0){
            throw new CustomException("信息绑定失败，result="+result);
        }
    }

    @Override
    public SysThirdPlatform selectSysThirdPlatformByCode(String platform) {
        return sysThirdPlatformMapper.selectSysThirdPlatformByCode(platform);
    }

    @Override
    public SysThird qqWebToThirdInfo(String code, String redirectUri) throws Exception {
        SysThirdPlatform alipayConfig = sysThirdPlatformMapper.selectSysThirdPlatformByCode("qq_pc");
        Map<String, String> accessTokenQuerys = Maps.newHashMap();
        accessTokenQuerys.put("grant_type", "authorization_code");
        accessTokenQuerys.put("appid", alipayConfig.getAppId());
        accessTokenQuerys.put("client_secret", alipayConfig.getAppSecret());
        accessTokenQuerys.put("code", code);
        accessTokenQuerys.put("redirect_uri", redirectUri);
        HttpResponse accessTokenResponse = HttpUtils.doGet("https://graph.qq.com", "/oauth2.0/token", null, accessTokenQuerys);
        JSONObject accessTokenResult = JSON.parseObject(EntityUtils.toString(accessTokenResponse.getEntity(), "UTF-8"));
        Map<String, String> unionIdQuerys = Maps.newHashMap();
        unionIdQuerys.put("access_tokenD", accessTokenResult.getString("access_token"));
        unionIdQuerys.put("unionid", "1");

        HttpResponse unionIdResponse = HttpUtils.doGet("https://graph.qq.com", "/oauth2.0/me", null, unionIdQuerys);
        JSONObject unionIdResult = JSON.parseObject(EntityUtils.toString(unionIdResponse.getEntity(), "UTF-8"));


        SysThird sysThird = thirdService.selectSysThirdByPlatform(alipayConfig.getPlatformCode(), unionIdResult.getString("openid"));
        if (sysThird == null) {
            sysThird = new SysThird();
            sysThird.setPlatform(alipayConfig.getPlatformCode());
//            sysThird.setOpenId(unionIdResult.getString("openid"));
//            sysThird.setUnionId(unionIdResult.getString("unionid"));
//            sysThird.setAccessToken(accessTokenResult.getString("access_token"));
//            sysThird.setRefreshToken(accessTokenResult.getString("refresh_token"));
//            sysThird.setExpiresIn(accessTokenResult.getString("expires_in"));
            thirdService.insertSysThird(sysThird);
        } else {
//            sysThird.setAccessToken(accessTokenResult.getString("access_token"));
//            sysThird.setRefreshToken(accessTokenResult.getString("refresh_token"));
//            sysThird.setExpiresIn(accessTokenResult.getString("expires_in"));
            thirdService.updateSysThird(sysThird);
        }
        return sysThird;
    }

    @Override
    public String qqToWebAuth(String redirectUri) throws Exception {
        SysThirdPlatform alipayConfig = sysThirdPlatformMapper.selectSysThirdPlatformByCode("qqWap");
        return "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" + alipayConfig.getAppId() + "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8") + "&state=test";
    }

    @Transactional
    @Override
    public SysThird qqAppToThirdInfo(String accessToken, String openId) throws Exception {
        SysThirdPlatform thirdPlatform = sysThirdPlatformMapper.selectSysThirdPlatformByCode("qq_app");

        Map<String, String> userInfoQuerys = Maps.newHashMap();
        userInfoQuerys.put("access_token", accessToken);
        userInfoQuerys.put("oauth_consumer_key", thirdPlatform.getAppId());
        userInfoQuerys.put("openid", openId);
        HttpResponse userInfoResponse = HttpUtils.doGet("https://graph.qq.com", "/user/get_user_info", null, userInfoQuerys);
        UserInfoQqBean userInfo = JSON.parseObject(EntityUtils.toString(userInfoResponse.getEntity(), "UTF-8"), UserInfoQqBean.class);

        Map<String,String> unionIDQuerys = Maps.newHashMap();
        unionIDQuerys.put("access_token",accessToken);
        unionIDQuerys.put("unionid","1");

        HttpResponse unionIdResponse = HttpUtils.doGet("https://graph.qq.com", "/oauth2.0/me", null, unionIDQuerys);
        String resultStr = EntityUtils.toString(unionIdResponse.getEntity(), "UTF-8");
        int l = resultStr.indexOf("(");
        int f = resultStr.indexOf(");");
        String subResultStr = resultStr.substring(l + 1, f);
        JSONObject unionIdResult = JSON.parseObject(subResultStr.trim());

        //相同平台下 唯一ID查询 查找用户
        SysThird unionSysThird = thirdService.selectSysThirdByUnionId(new String[]{"qq_app", "qq_pc"}, unionIdResult.getString("unionid"));

        //查找第三方帐号是否存在
        SysThird oldSysThird = thirdService.selectSysThirdByPlatform("qq_app", openId);

        if (oldSysThird == null){
            SysUser sysUser = null;
            SysThird sysThird = new SysThird();
            if (unionSysThird == null){
                sysUser = new SysUser();
                sysUser.setNickName(userInfo.getNickname());
                sysUser.setAvatar(userInfo.getFigureurl_qq_1());
                sysUser.setUserType(UserTypeEnum.MEMBER.getCode());
                if (userInfo.getGender().equals("女")){
                    sysUser.setSex("1");
                }
                if (userInfo.getGender().equals("男")){
                    sysUser.setSex("0");
                }
                sysUser.setStatus(StatusEnum.OK.getCode());
                sysUserService.insertUser(sysUser);
                sysThird.setUserId(sysUser.getUserId());
            }else{
                sysThird.setUserId(unionSysThird.getUserId());
            }
            sysThird.setPlatform(thirdPlatform.getPlatformCode());
//            sysThird.setOpenId(unionIdResult.getString("openid"));
//            sysThird.setUnionId(unionIdResult.getString("unionid"));
//            sysThird.setOpenName(userInfo.getNickname());
//            sysThird.setAccessToken(accessToken);
            thirdService.insertSysThird(sysThird);
            return sysThird;
        }else{
//            oldSysThird.setAccessToken(accessToken);
//            oldSysThird.setOpenName(userInfo.getNickname());
            thirdService.updateSysThird(oldSysThird);

            SysUser sysUser = sysUserService.selectUserById(oldSysThird.getUserId());
            sysUser.setAvatar(userInfo.getFigureurl_qq_1());
            sysUserService.updateUser(sysUser);
            return oldSysThird;
        }
    }


    //public SysThird wxMinToThirdInfo(String encryptedData, String iv, String code) throws Exception {
    @Transactional(rollbackFor = Exception.class)
    @Override
//    public SysThird wxMinToThirdInfo(String encryptedData, String iv, String code) throws Exception {
    public SysThird wxMinToThirdInfo(String encryptedData, String iv, String sessionKey) throws Exception {
//        SysThirdPlatform thirdPlatform = sysThirdPlatformMapper.selectSysThirdPlatformByCode("wx_miniapp");
//
//        Map<String, String> jscode2SessionQuerys = Maps.newHashMap();
//        jscode2SessionQuerys.put("appid", thirdPlatform.getAppId());
//        jscode2SessionQuerys.put("secret", thirdPlatform.getAppSecret());
//        jscode2SessionQuerys.put("js_code", code);
//        jscode2SessionQuerys.put("grant_type","authorization_code");
//        HttpResponse jscode2SessionResponse = HttpUtils.doGet("https://api.weixin.qq.com", "/sns/jscode2session", null, jscode2SessionQuerys);
//        Jscode2SessionBean jscode2Session = JSON.parseObject(EntityUtils.toString(jscode2SessionResponse.getEntity(), "UTF-8"),Jscode2SessionBean.class);
//        if(StringUtils.isBlank(jscode2Session.getOpenid())&&StringUtils.isBlank(jscode2Session.getSessionKey())){
//            throw new CustomException("未获取到用户openid 或 session:"+JSON.toJSONString(jscode2Session));
//        }
        //解密获取用户信息
//        String result = MiniappUtils.wxDecrypt(encryptedData, jscode2Session.getSessionKey(), iv);
        String result = MiniappUtils.wxDecrypt(encryptedData, sessionKey, iv);
        UserInfoBean userInfo = JSON.parseObject(result, UserInfoBean.class);
        if(userInfo == null){
            throw new CustomException("解密用户信息异常");
        }
        //相同平台下 唯一ID查询 查找用户
        //SysThird unionSysThird = thirdService.selectSysThirdByUnionId(new String[]{"wx_miniapp", "wx_app", "wx_pc"}, jscode2Session.getUnionid());
        //小程序
        SysThird unionSysThird = thirdService.selectSysThirdByCode("wx", userInfo.getUnionId());
        if (unionSysThird == null){
            SysThird sysThird = new SysThird();
            SysUser sysUser = new SysUser();
            sysUser.setNickName(userInfo.getNickName());
            sysUser.setUserName(userInfo.getNickName());
            sysUser.setAvatar(userInfo.getAvatarUrl());
            if (userInfo.getGender().equals("0")){
                sysUser.setSex("2");
            }
            if (userInfo.getGender().equals("1")){
                sysUser.setSex("0");
            }
            if (userInfo.getGender().equals("2")){
                sysUser.setSex("1");
            }
            sysUser.setUserType(UserTypeEnum.MEMBER.getCode());
            sysUser.setStatus(StatusEnum.OK.getCode());
            sysUser.setOpenId(userInfo.getOpenId());
            sysUserService.insertUser(sysUser);
            sysThird.setUserId(sysUser.getUserId());
            sysThird.setOpenId(userInfo.getOpenId());
            sysThird.setPlatform("wx");
            sysThird.setCode(userInfo.getUnionId());
            sysThird.setLoginTime(DateUtils.getNowDate());
//            sysThird.setSessionKey(jscode2Session.getSessionKey());
            sysThird.setSessionKey(sessionKey);
            thirdService.insertSysThird(sysThird);

            //绑定小程序openId
            UserBindGsd userBindGsd = new UserBindGsd();
            userBindGsd.setAvatar(userInfo.getAvatarUrl());
            userBindGsd.setPlatform("wx_mini");
            userBindGsd.setRealUserName(userInfo.getNickName());
            userBindGsd.setUniqueId(userInfo.getOpenId());
            userBindGsd.setUserId(sysUser.getUserId());
            userBindGsd.setIsBind("1");
            userBindGsd.setCreateTime(new Date());
            userBindGsdMapper.insertUserBindGsd(userBindGsd);

            return sysThird;
        }else{
            SysUser sysUser = sysUserService.selectUserById(unionSysThird.getUserId());
            if (sysUser !=null){
                if (StringUtils.isEmpty(sysUser.getOpenId())){
                    sysUser.setOpenId(userInfo.getOpenId());
                }
                //更新用户信息
                sysUser.setNickName(userInfo.getNickName());
                sysUser.setAvatar(userInfo.getAvatarUrl());
                sysUser.setUpdateTime(DateUtils.getNowDate());
                sysUserService.updateUser(sysUser);

                //判断是否绑定过
                UserBindGsd userBindGsd = userBindGsdMapper.selectUserBindGsdByUserIdAndPlatform(sysUser.getUserId(), "wx_mini");
                if (userBindGsd == null){
                    //绑定小程序openId
                    userBindGsd = new UserBindGsd();
                    userBindGsd.setAvatar(userInfo.getAvatarUrl());
                    userBindGsd.setPlatform("wx_mini");
                    userBindGsd.setRealUserName(userInfo.getNickName());
                    userBindGsd.setUniqueId(userInfo.getOpenId());
                    userBindGsd.setUserId(sysUser.getUserId());
                    userBindGsd.setIsBind("1");
                    userBindGsd.setCreateTime(new Date());
                    userBindGsdMapper.insertUserBindGsd(userBindGsd);
                }
            }
            //更新第三信息
            unionSysThird.setLoginTime(DateUtils.getNowDate());
            unionSysThird.setCode(userInfo.getUnionId());
            unionSysThird.setOpenId(userInfo.getOpenId());
//            unionSysThird.setSessionKey(jscode2Session.getSessionKey());
            unionSysThird.setSessionKey(sessionKey);
            thirdService.updateSysThird(unionSysThird);

            return unionSysThird;
        }
    }



//    @Override
//    public SysThird wxWebToThirdInfo(String code) throws Exception {
//        return this.wxToThirdInfo(code,"wx_web");
//    }
//
//    @Override
//    public SysThird wxAppToThirdInfo(String code) throws Exception {
//        return wxToThirdInfo(code,"wx_app");
//    }
//
//    @Override
//    @Transactional
//    public SysThird wxAppToThirdInfo(String unionid) throws Exception {
//        return wxToThirdInfo(unionid);
//    }

    private SysThird wxToThirdInfo(String code,String platofrm) throws Exception{
        SysThirdPlatform thirdPlatform = sysThirdPlatformMapper.selectSysThirdPlatformByCode(platofrm);
        Map<String, String> querys = Maps.newHashMap();
        querys.put("appid", thirdPlatform.getAppId());
        querys.put("secret", thirdPlatform.getAppSecret());
        querys.put("code", code);
        querys.put("grant_type","authorization_code");
        HttpResponse accessTokenResponse = HttpUtils.doGet("https://api.weixin.qq.com", "/sns/oauth2/access_token", null, querys);
        AccessTokenBean accessToken = JSON.parseObject(EntityUtils.toString(accessTokenResponse.getEntity(), "UTF-8"),AccessTokenBean.class);
        if(StringUtils.isBlank(accessToken.getOpenid())&&StringUtils.isBlank(accessToken.getAccessToken())){
            throw new CustomException("未获取到用户openid 或 token:"+JSON.toJSONString(accessToken));
        }

        querys = Maps.newHashMap();
        querys.put("access_token",accessToken.getAccessToken());
        querys.put("openid",accessToken.getOpenid());
        HttpResponse userinfoResponse = HttpUtils.doGet("https://api.weixin.qq.com", "/sns/userinfo", null, querys);
        JSONObject userinfoObject = JSON.parseObject(EntityUtils.toString(userinfoResponse.getEntity(), "UTF-8"));

        //相同平台下 唯一ID查询 查找用户
        SysThird unionSysThird = thirdService.selectSysThirdByUnionId(new String[]{"wx_mini", "wx_app", "wx_pc"}, userinfoObject.getString("unionid"));

        //查找第三方帐号是否存在
        SysThird oldSysThird = thirdService.selectSysThirdByPlatform(platofrm, userinfoObject.getString("openid"));
        if (oldSysThird == null){
            SysUser sysUser = null;
            SysThird sysThird = new SysThird();
            if (unionSysThird == null){
                sysUser = new SysUser();
                sysUser.setNickName(userinfoObject.getString("nickname"));
                sysUser.setAvatar(userinfoObject.getString("headimgurl"));
                sysUser.setUserType(UserTypeEnum.MEMBER.getCode());
                if (userinfoObject.getString("sex").equals("0")){
                    sysUser.setSex("2");
                }
                if (userinfoObject.getString("sex").equals("1")){
                    sysUser.setSex("0");
                }
                if (userinfoObject.getString("sex").equals("2")){
                    sysUser.setSex("1");
                }
                sysUser.setStatus(StatusEnum.OK.getCode());
                sysUserService.insertUser(sysUser);
                sysThird.setUserId(sysUser.getUserId());
            }else{
                sysThird.setUserId(unionSysThird.getUserId());
            }
            sysThird.setPlatform(thirdPlatform.getPlatformCode());
//            sysThird.setOpenId(userinfoObject.getString("openid"));
//            sysThird.setUnionId(userinfoObject.getString("unionid"));
//            sysThird.setOpenName(userinfoObject.getString("nickname"));
//            sysThird.setAccessToken(accessToken.getAccessToken());
//            sysThird.setRefreshToken(accessToken.getRefreshToken());
//            sysThird.setExpiresIn(accessToken.getExpiresIn());
            thirdService.insertSysThird(sysThird);
            return sysThird;
        }else{
//            oldSysThird.setAccessToken(accessToken.getAccessToken());
//            oldSysThird.setRefreshToken(accessToken.getRefreshToken());
//            oldSysThird.setExpiresIn(accessToken.getExpiresIn());
//            oldSysThird.setOpenName(userinfoObject.getString("nickname"));
            thirdService.updateSysThird(oldSysThird);

            SysUser sysUser = sysUserService.selectUserById(oldSysThird.getUserId());
            sysUser.setAvatar(userinfoObject.getString("headimgurl"));
            sysUserService.updateUser(sysUser);
            return oldSysThird;
        }
    }

    @Override
    @Transactional
    public SysThird appToThirdInfo(String code, String platform) {
        return toThirdInfo(code,platform);
    }


    public SysThird toThirdInfo(String code,String platform){
        //相同平台下 唯一ID查询 查找用户
        SysThird unionSysThird = thirdService.selectSysThirdByCode(platform, code);


        if (unionSysThird == null){
            SysThird sysThird = new SysThird();
            SysUser sysUser = new SysUser();
            sysUser.setNickName("Ngsd"+UUID.randomUUID().toString().substring(0,6));
            sysUser.setUserName("Ugsd"+UUID.randomUUID().toString().substring(0,6));
            sysUser.setAvatar("https://backage.gsd520.com/profile/image/040f9d3583484fca94bca1850cde1dfb.jpeg");
            sysUser.setUserType(UserTypeEnum.MEMBER.getCode());
            sysUser.setStatus(StatusEnum.OK.getCode());
            sysUserService.insertUser(sysUser);
            sysThird.setUserId(sysUser.getUserId());
            sysThird.setPlatform(platform);
            sysThird.setCode(code);
            sysThird.setLoginTime(DateUtils.getNowDate());
            thirdService.insertSysThird(sysThird);
            return sysThird;
        }else{
            unionSysThird.setLoginTime(DateUtils.getNowDate());
            unionSysThird.setCode(code);
            thirdService.updateSysThird(unionSysThird);

            return unionSysThird;
        }
    }
}
